const Service = require("egg").Service;

class Commodity_type extends Service {
  // 查询分类列表
  async getCommodityTypeList() {
    let Commoditytype = await this.app.model.Commoditytype.findAll();

    return Commoditytype;
  }

  // 添加分类
  async addCommodityType() {
    let { type_name } = this.ctx.request.body;

    if (await this.app.model.Commoditytype.findOne({ where: { type_name } })) {
      return {
        msg: "分类名称已存在"
      };
    }

    let res = await this.app.model.Commoditytype.create({ type_name });

    if (!res)
      return {
        msg: "添加失败"
      };

    return {
      msg: "添加成功"
    };
  }

  // 修改分类名称
  async updateCommodityType() {
    let id = this.ctx.params.id;
    let type_name = this.ctx.request.body.type_name;
    if (await this.app.model.Commoditytype.findOne({ where: { type_name } })) {
      return {
        msg: "分类名称已存在"
      };
    }

    let res = await this.app.model.Commoditytype.update(
      { type_name },
      {
        where: {
          id
        }
      }
    );

    if (!res) return { msg: "修改失败" };

    return {
      msg: "修改成功"
    };
  }

  async deleteCommodityType() {
    let id = this.ctx.params.id;
    let res = await this.app.model.Commoditytype.destroy({ where: { id } });
    if (!res) return { msg: "删除失败" };

    return {
      msg: "删除成功"
    };
  }
}
module.exports = Commodity_type;
